package com.api.customization.huangwm.dao.SW003;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.LogTool;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.entity.publicApi.WorkflowDetailTableInfoEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import org.apache.commons.lang.StringEscapeUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.webservices.WorkflowRequestTableField;
import weaver.workflow.webservices.WorkflowRequestTableRecord;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022-05-04
 * @Version 1.0
 * @Description TODO 物料、资产信息操作数据
 **/
public class AssetInfoOperationDao extends BaseBean {
    private LogTool log = new LogTool("/log/SW003/huangwm/dao/AssetInfoOperation", false);
    private DBTools dbTools = new DBTools();
    public final String assetTable = "uf_003_AssteInfo";
    public final String tableKey = "assetCode";
    private LoggingDao loggingDao = new LoggingDao();
    private DateTools dateTools = new DateTools();
    private String apiPath = "/api/customization/SW003/assetOperation";

    /**
     * 新增物料信息
     * @param requestParams
     * @return
     */
    public Map<String, Object> Save(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("新增物料信息參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "保存物料缺少必要參數datas");
            loggingDao.wrtieLog("1", apiPath + "/save", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            result.put("apiStatus", false);
            return result;
        }
        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/save", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        Map<String, Object> check = checkDetailsForSave(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/save", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        String uf_003_AssteInfo_Modeid = getPropValue("SW003", "uf_003_AssteInfo_Modeid");
        String sql = "insert into " + assetTable + "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID,assetCode,assetName,assetDescribe,unit,manageDep,assetModel,assetType,isAsset,totalQuantity,usedQuantity,InventoryQuantity)"
                + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        List<List<Object>> paramsList = new ArrayList<>();
        for (Map<String, String> data : datas) {
            List<Object> param = new ArrayList<>();
            String assetCode = data.get("assetCode");
            String assetName = data.get("assetName"),
                    assetDescribe = data.get("assetDescribe"),
                    unit = data.get("unit"),
                    manageDep = data.getOrDefault("manageDep", ""),
                    assetModel = data.get("assetModel"),
                    assetType = data.get("assetType"),
                    isAsset = data.getOrDefault("isAsset", "N");
            String totalQuantity = data.getOrDefault("totalQuantity", "0");
            String usedQuantity = data.getOrDefault("usedQuantity", "0");
            String InventoryQuantity = data.getOrDefault("InventoryQuantity", "0");
            param.add(uf_003_AssteInfo_Modeid);
            param.add(1);
            param.add(0);
            param.add(dateTools.getCurrentDate());
            param.add(dateTools.getCurrentTime());
            param.add(dateTools.getUUID());
            param.add(assetCode);
            param.add(assetName);
            param.add("");//不传描述
            param.add(getAssetUnit(unit));
            param.add(getDepartmentid(manageDep));
            param.add(assetModel);
            param.add(getAssetType(assetType));
            param.add(isAsset.equals("Y") ? 0 : 1);
            param.add(totalQuantity);
            param.add(usedQuantity);
            param.add(InventoryQuantity.isEmpty() ? (Integer.parseInt(totalQuantity) - Integer.parseInt(usedQuantity)) : InventoryQuantity);

            paramsList.add(param);
        }
        RecordSetTrans rs = new RecordSetTrans();
        rs.setAutoCommit(false);
        try {
            rs.executeBatchSql(sql, paramsList);
        } catch (Exception e) {
            rs.rollback();
            e.printStackTrace();
            result.put("msg", "保存物料信息執行SQL異常 \n" + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/save", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        log.writeLog("权限重构开始=>>>" + dateTools.getCurrentTimes());
        RecordSet getMaxid = new RecordSet();
        getMaxid.execute("select max(id) as maxid from " + assetTable);
        getMaxid.next();
        int maxid = getMaxid.getInt("maxid");
        for (int i = maxid; i > maxid - paramsList.size(); i--) {
            dbTools.refreshRight(1, Util.getIntValue(uf_003_AssteInfo_Modeid, 0), i);
        }
        log.writeLog("权限重构结束=>>>" + dateTools.getCurrentTimes());
        loggingDao.wrtieLog("1", apiPath + "/save", JSON.toJSONString(requestParams), JSON.toJSONString(result));
        rs.commit();
        return result;
    }

    /**
     * 更新物料信息
     * @param requestParams
     * @return
     */
    public Map<String, Object> Update(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("更新物料信息參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "物料狀態更新缺少必要參數datas");
            loggingDao.wrtieLog("1", apiPath + "/update", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            result.put("apiStatus", false);
            return result;
        }
        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/update", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        Map<String, Object> check = checkDetails(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/update", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        String sql = "update " + assetTable + " set assetName=?,unit=?,assetModel=?,assetType=? where " + tableKey + "=?";
        List<List<Object>> paramsList = new ArrayList<>();
        for (Map<String, String> data : datas) {
            List<Object> param = new ArrayList<>();
            String assetCode = data.get("assetCode");
            String assetName = data.get("assetName"),
                    assetDescribe = data.get("assetDescribe"),
                    unit = data.get("unit"),
                    manageDep = data.getOrDefault("manageDep", ""),
                    assetModel = data.get("assetModel"),
                    assetType = data.get("assetType");
            param.add(assetName);
            //param.add("assetDescribe");//不传描述
            param.add(getAssetUnit(unit));
            //param.add(getDepartmentid(manageDep));
            param.add(assetModel);
            param.add(getAssetType(assetType));
            param.add(assetCode);

            paramsList.add(param);
        }
        RecordSetTrans rs = new RecordSetTrans();
        rs.setAutoCommit(false);
        try {
            rs.executeBatchSql(sql, paramsList);
        } catch (Exception e) {
            rs.rollback();
            e.printStackTrace();
            result.put("msg", "更新物料信息執行SQL異常 \n" + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/update", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        loggingDao.wrtieLog("1", apiPath + "/update", JSON.toJSONString(requestParams), JSON.toJSONString(result));
        rs.commit();
        return result;
    }

    /**
     * 更新物料状态-封存，解封
     * @param requestParams
     * @return
     */
    public Map<String, Object> Status(Map<String, Object> requestParams){
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("封存、解封物料參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "物料状态更新时缺少必要参数datas");
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            result.put("apiStatus", false);
            return result;
        }
        Map<String, String> datas = new HashMap<>();
        try {
            //datas = (Map<String, String>) requestParams.get("datas");
            datas = (Map<String, String>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        //sealed封存 unseal解封
        String action = "";
        if (!datas.containsKey("action")) {
            result.put("msg", "datas中缺少參數action");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        action = datas.get("action");
        if (!datas.containsKey("assetCode")) {
            result.put("msg", "datas中缺少參數assetCode");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        if (!action.equals("sealed") && !action.equals("unseal")) {
            result.put("msg", "datas>action参数需为sealed或unseal[" + action + "]");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        Map<String, Object> check = checkMain(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        RecordSetTrans rs = new RecordSetTrans();
        rs.setAutoCommit(false);
        try {
            rs.execute("update " + assetTable + " set assetStatus=" + (datas.get("action").equals("unseal") ? "0" : "1") + " where " + tableKey + "='" + datas.get("assetCode") + "'");
        } catch (Exception e) {
            rs.rollback();
            e.printStackTrace();
            result.put("msg", "更新物料状态执行SQL异常 " + e.getStackTrace());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        loggingDao.wrtieLog("1", apiPath + "/status", JSON.toJSONString(requestParams), JSON.toJSONString(result));
        rs.commit();
        return result;
    }

    /**
     * 更新库存
     * @param requestParams action into=入庫 out=出庫
     * @return
     */
    public Map<String, Object> UpdateInventory(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("更新物料庫存參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "物料库存更新时缺少必要参数datas");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
//        Map<String, String> datas = new HashMap<>();
//        try {
//            //datas = (Map<String, String>) requestParams.get("datas");
//            datas = (Map<String, String>) JSONObject.parse(requestParams.get("datas").toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
//            result.put("apiStatus", false);
//            return result;
//        }

        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        Map<String, Object> check = checkDetails(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        //檢查物料庫存
        RecordSet checkQuantity = new RecordSet();
        List<Map<String, String>> logList = new ArrayList<>();//日志记录
        String sql = "";//更新物料庫存
        int i=1;
        RecordSet rs = new RecordSet();
        try {
            for (Map<String, String> data : datas) {
                String action = data.get("action");
                 /**
                  用友传的action是into，但是quantity是负数的时候，OA这边做出库处理；
                  action是into，quantity正式为入库
                  action为out，但是quantity是负数的时候OA做入库处理，quantity为正数的时候则为出库
                  **/
                if (!data.containsKey("action") || action.isEmpty()) {
                    result.put("msg", "datas中第" + i + "行["+JSONObject.toJSONString(data)+"]缺少參數action");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
                if (!action.equals("out") && !action.equals("into")) {
                    result.put("msg", "datas中第" + i + "行["+JSONObject.toJSONString(data)+"]參數action必須為out或into");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
                String assetCode = data.get("assetCode");
                Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(rs,assetCode);

                String assetid = assetInfo.get("id");//物料id

                String requestNumber = data.get("requestNumber"), reason = data.get("reason");
                Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
                sql = "update " + assetTable + " set usedQuantity=usedQuantity" + (action.equals("into") ? "-" : "+") + (action.equals("into") ? 0 : Math.abs(quantity)) + ",InventoryQuantity=InventoryQuantity" + (action.equals("into") ? "+" : "-") + Math.abs(quantity) + ",totalQuantity=totalQuantity" + (action.equals("into") ? "+" : "-") + (action.equals("into") ? Math.abs(quantity) : 0) + " where " + tableKey + "='" + assetCode + "'";
                checkQuantity.execute("select * from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
                checkQuantity.next();
                Double InventoryQuantity = checkQuantity.getDouble("InventoryQuantity");

                if (action.equals("out") && InventoryQuantity < Math.abs(quantity)) {
                    result.put("msg", action+" EAP中物料[" + assetCode + "]當前庫存為[" + InventoryQuantity + "],不足出庫本次數量[" + Math.abs(quantity) + "]");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                } else {
                    boolean result1 = rst.execute(sql);
                    log.writeLog("執行更新物料庫存SQL：" + sql);
                    log.writeLog("執行結果：" + result1);
                    if(!result1){
                        rst.rollback();
                        result.put("msg", action+" EAP中物料[" + assetCode + "]更新庫存失敗");
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                    //20221017 新增出入庫時操作默認倉庫庫存
                    //num1總庫存
                    //num2已出庫
                    //num3剩餘庫存
                    //num4出庫中
                    String wareHouse = dbTools.getAssetInfoByCode(checkQuantity,assetCode,"wareHouse");
                    boolean thisCheck = true;
                    if(action.equals("out")){
                        //出庫 剩餘庫存減少 已出庫增加
                        //出库时传过来的是负数  转化为绝对值
                        String wareHouseSql = "update uf_003_WarehouseNum set num3=NVL(num3,0)-"+Math.abs(quantity)+",num2=NVL(num2,0)+"+Math.abs(quantity) +" where assetCode="+assetid+" and wareHouse="+wareHouse;
                        log.writeLog("出庫更新倉庫庫存："+wareHouseSql);
                        thisCheck = rst.execute(wareHouseSql);
                    }else{
                        //入庫 已出庫減少 剩餘庫存增加
                        //入库时传过来的是负数  转化为绝对值
                        String wareHouseSql = "update uf_003_WarehouseNum set num2=NVL(num2,0)-"+Math.abs(quantity)+",num3=NVL(num3,0)+"+Math.abs(quantity) +" where assetCode="+assetid+" and wareHouse="+wareHouse;
                        log.writeLog("入庫更新倉庫庫存："+wareHouseSql);
                        thisCheck = rst.execute(wareHouseSql);
                    }
                    if(!thisCheck){
                        result.put("msg", action+" EAP中物料[" + assetCode + "]更新倉庫["+wareHouse+"]庫存失敗");
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("0", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                    Map<String, String> logMap = new HashMap();
                    logMap.put("assetCode", assetCode);
                    logMap.put("assetName", assetInfo.get("assetname"));
                    logMap.put("quantity", Math.abs(quantity)+"");
                    logMap.put("requestNumber", requestNumber);
                    logMap.put("reason",reason);
                    logMap.put("type",action.equals("into")?"0":"1");
                    logList.add(logMap);
                    i++;
                }
            }
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            for (int j = 0; j < logList.size(); j++) {
                Map<String, String> log = logList.get(j);
                loggingDao.wrtieInventoryLog(rst,"1", log.get("assetCode"), Double.parseDouble(log.get("quantity")), log.get("requestNumber"), log.get("reason"),"","",
                        log.get("type"),"","",log.get("assetName"));
            }
            rst.commit();
            return result;
        } catch (Exception e) {
            rst.rollback();
            e.printStackTrace();
            result.put("msg", "更新物料库存执行SQL异常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        //return result;
    }

    /**
     * 更新库存V2 20230308调整逻辑
     * @param requestParams action into=入庫 out=出庫
     * @return
     */
    public Map<String, Object> UpdateInventoryV2(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("更新物料庫存參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "物料库存更新时缺少必要参数datas");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
//        Map<String, String> datas = new HashMap<>();
//        try {
//            //datas = (Map<String, String>) requestParams.get("datas");
//            datas = (Map<String, String>) JSONObject.parse(requestParams.get("datas").toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
//            result.put("apiStatus", false);
//            return result;
//        }

        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        Map<String, Object> check = checkDetails(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        //檢查物料庫存
        RecordSet checkQuantity = new RecordSet();
        List<Map<String, String>> logList = new ArrayList<>();//日志记录

        int i=1;
        RecordSet rs = new RecordSet();
        try {
            for (Map<String, String> data : datas) {
                String action = data.get("action");
                String sql = "";//更新物料庫存
                String wareHouseSql = "";
                /**
                 用友传的action是into，但是quantity是负数的时候，OA这边做出库处理；
                 action是into，quantity正式为入库
                 action为out，但是quantity是负数的时候OA做入库处理，quantity为正数的时候则为出库
                 **/
                if (!data.containsKey("action") || action.isEmpty()) {
                    result.put("msg", "datas中第" + i + "行["+JSONObject.toJSONString(data)+"]缺少參數action");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
                if (!action.equals("out") && !action.equals("into")) {
                    result.put("msg", "datas中第" + i + "行["+JSONObject.toJSONString(data)+"]參數action必須為out或into");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
                String assetCode = data.get("assetCode");
                Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(rs,assetCode);

                String assetid = assetInfo.get("id");//物料id

                String requestNumber = data.get("requestNumber"), reason = data.get("reason");
                Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
                //入库
                if(action.equals("into")&&quantity>=0){
                    sql = "update "+assetTable+" set usedQuantity=usedQuantity-"+Math.abs(quantity)+"," +
                            "InventoryQuantity=InventoryQuantity+"+Math.abs(quantity)+"  where "+tableKey+"='"+assetCode+"'";
                }
                //出库
                else if(action.equals("into")&&quantity<0){
                    sql = "update "+assetTable+" set usedQuantity=usedQuantity+"+Math.abs(quantity)+"," +
                            "InventoryQuantity=InventoryQuantity-"+Math.abs(quantity)+"  where "+tableKey+"='"+assetCode+"'";
                }
                //出库
                else if(action.equals("out")&&quantity>=0){
                    sql = "update "+assetTable+" set usedQuantity=usedQuantity+"+Math.abs(quantity)+"," +
                            "InventoryQuantity=InventoryQuantity-"+Math.abs(quantity)+"  where "+tableKey+"='"+assetCode+"'";
                }
                //入库
                else if(action.equals("out")&&quantity<0){
                    sql = "update "+assetTable+" set usedQuantity=usedQuantity-"+Math.abs(quantity)+"," +
                            "InventoryQuantity=InventoryQuantity+"+Math.abs(quantity)+"  where "+tableKey+"='"+assetCode+"'";
                }

                checkQuantity.execute("select * from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
                checkQuantity.next();
                Double InventoryQuantity = checkQuantity.getDouble("InventoryQuantity");

                if (((action.equals("out")&&quantity>=0) || action.equals("into")&&quantity<0 )
                        && InventoryQuantity < Math.abs(quantity)) {
                    result.put("msg", action+" EAP中物料[" + assetCode + "]當前庫存為[" + InventoryQuantity + "],不足出庫本次數量[" + Math.abs(quantity) + "]");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                } else {
                    boolean result1 = rst.execute(sql);
                    log.writeLog("執行更新物料庫存SQL：" + sql);
                    log.writeLog("執行結果：" + result1);
                    if(!result1){
                        rst.rollback();
                        result.put("msg", action+" EAP中物料[" + assetCode + "]更新庫存失敗");
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                    //20221017 新增出入庫時操作默認倉庫庫存
                    //num1總庫存
                    //num2已出庫
                    //num3剩餘庫存
                    //num4出庫中
                    String wareHouse = dbTools.getAssetInfoByCode(checkQuantity,assetCode,"wareHouse");
                    boolean thisCheck = true;
                    String log_type = "";
                    //入库 已出庫減少 剩餘庫存增加
                    if(action.equals("into")&&quantity>=0){
                        wareHouseSql = "update uf_003_WarehouseNum set num3=NVL(num3,0)+"+Math.abs(quantity)+",num2=NVL(num2,0)-"+Math.abs(quantity)+"  where assetCode='"+assetid+"' and wareHouse="+wareHouse;
                        log.writeLog("入庫更新倉庫庫存："+wareHouseSql);
                        thisCheck = rst.execute(wareHouseSql);
                        log_type = "0";
                    }
                    //出库 剩餘庫存減少 已出庫增加
                    else if(action.equals("into")&&quantity<0){
                        wareHouseSql = "update uf_003_WarehouseNum set num3=NVL(num3,0)-"+Math.abs(quantity)+",num2=NVL(num2,0)+"+Math.abs(quantity)+"  where assetCode='"+assetid+"' and wareHouse="+wareHouse;
                        log.writeLog("出庫更新倉庫庫存："+wareHouseSql);
                        thisCheck = rst.execute(wareHouseSql);
                        log_type = "1";
                    }
                    //出库 剩餘庫存減少 已出庫增加
                    else if(action.equals("out")&&quantity>=0){
                        wareHouseSql = "update uf_003_WarehouseNum set num3=NVL(num3,0)-"+Math.abs(quantity)+",num2=NVL(num2,0)+"+Math.abs(quantity)+"  where assetCode='"+assetid+"' and wareHouse="+wareHouse;
                        log.writeLog("出庫更新倉庫庫存："+wareHouseSql);
                        thisCheck = rst.execute(wareHouseSql);
                        log_type = "1";
                    }
                    //入库 已出庫減少 剩餘庫存增加
                    else if(action.equals("out")&&quantity<0){
                        wareHouseSql = "update uf_003_WarehouseNum set num3=NVL(num3,0)+"+Math.abs(quantity)+",num2=NVL(num2,0)-"+Math.abs(quantity)+"  where assetCode='"+assetid+"' and wareHouse="+wareHouse;
                        log.writeLog("入庫更新倉庫庫存："+wareHouseSql);
                        thisCheck = rst.execute(wareHouseSql);
                        log_type = "0";
                    }
                    if(!thisCheck){
                        result.put("msg", action+" EAP中物料[" + assetCode + "]更新倉庫["+wareHouse+"]庫存失敗");
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("0", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                    Map<String, String> logMap = new HashMap();
                    logMap.put("assetCode", assetCode);
                    logMap.put("assetName", assetInfo.get("assetname"));
                    logMap.put("quantity", Math.abs(quantity)+"");
                    logMap.put("requestNumber", requestNumber);
                    logMap.put("reason",reason);
                    logMap.put("type",log_type);
                    logMap.put("field1",wareHouse);
                    logMap.put("field2","");
                    logMap.put("userid","");
                    logList.add(logMap);
                    i++;
                }
            }

            try{
                loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                for (int j = 0; j < logList.size(); j++) {
                    Map<String, String> log = logList.get(j);
                    loggingDao.wrtieInventoryLog(rst,"1", log.get("assetCode"), Double.parseDouble(log.get("quantity")), log.get("requestNumber"), log.get("reason"),log.get("field1"),"",
                            log.get("type"),log.get("userid"),"",log.get("assetName"));
                }
            }catch (Exception e){
                rst.rollback();
                result.put("msg", "更新物料库存记录日志异常 \n" + e.getMessage());
                result.put("apiStatus", false);
                return result;
            }

            rst.commit();
            return result;
        } catch (Exception e) {
            rst.rollback();
            e.printStackTrace();
            result.put("msg", "更新物料库存执行SQL异常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/updateInventory", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        //return result;
    }

    /**
     * 采購入庫 isAsset為Y时插入到采購入庫記錄，為N时將數量更新到物料表庫存中並記錄日志，同時也徐插入采購入庫記錄
     * @param requestParams
     * @return
     */
    public Map<String, Object> PurchaseStorage(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("采購入庫參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "采購入庫缺少必要参数datas");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        String poNo = "";
        if (!requestParams.containsKey("poNo")) {
            result.put("msg", "采購入庫缺少必要参数poNo");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        //poNo = String.valueOf(requestParams.get("poNo")).replace("\"","");
        poNo = StringEscapeUtils.unescapeJava((String) requestParams.get("poNo"));
        if (poNo.isEmpty()) {
            result.put("msg", "采購入庫参数poNo為空請檢查");
            result.put("apiStatus", false);
            return result;
        }
        String prid = "";
        //2023年3月21日 修改允许prid为空
//        if (!requestParams.containsKey("prid")) {
//            result.put("msg", "采購入庫缺少必要参数prid");
//            result.put("apiStatus", false);
//            loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
//            return result;
//        }
        String prTable = getPropValue("SW003","prTable");
        if(requestParams.containsKey("prid")){
            prid = requestParams.get("prid").toString().replace("\"","");
//            if (prid.isEmpty()) {
//                result.put("msg", "采購入庫参数prid為空請檢查");
//                result.put("apiStatus", false);
//                loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
//                return result;
//            }
            //根据requestid查询PR
            //String prTable = dbTools.getBillTableName(prid);
            if(prTable.isEmpty()){
                result.put("msg", "获取SW003.properties中的prTable为空");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            if(!prid.isEmpty()){
                RecordSet checkPR = new RecordSet();
                checkPR.execute("select requestid,id from "+prTable+" where requestid="+prid);
                log.writeLog("select requestid,id from "+prTable+" where requestid="+prid);
                if(!checkPR.next()){
                    result.put("msg", "根据prid["+prid+"]查询pr流程["+prTable+"]为空");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }
        }

        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        Map<String, Object> check = checkDetails(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        String uf_003_yyArrivalRecord_Modeid = getPropValue("SW003", "uf_003_yyArrivalRecord_Modeid");
        String sql_0 = "insert into uf_003_yyArrivalRecord"
                + "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID"
                + ",eapItemCode,itemcode,assetName,assetDescribe,unit,isAsset,manageDep,assetModel,assetType,quantity,locationCode,locationDescribe"
                + ",brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,assetNums,thisSouce,prid,dateStr,wereHouse)"
                + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        String sql_1 = "update " + assetTable + " set totalQuantity=totalQuantity + ?,InventoryQuantity=InventoryQuantity + ? where " + tableKey + "=?";
        List<List<Object>> paramsList_0 = new ArrayList<>();//是资产的数据插入
        List<List<Object>> paramsList_1 = new ArrayList<>();//不是资产的数据插入
        List<Map<String, String>> logList = new ArrayList<>();//日志记录
        RecordSet newRs = new RecordSet();
        RecordSet get = new RecordSet();
        RecordSetTrans set = new RecordSetTrans();
        set.setAutoCommit(false);
        for (Map<String, String> data : datas) {
            List<Object> param_0 = new ArrayList<>();
            List<Object> param_1 = new ArrayList<>();
            String assetCode = data.get("assetCode");
            Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(newRs,assetCode);
//            String assetName = data.getOrDefault("assetName",assetInfo.get("assetname")),
//                    assetDescribe = data.getOrDefault("assetDescribe",assetInfo.get("assetdescribe")),
//                    unit = data.getOrDefault("unit",assetInfo.get("unit")),
//                    manageDep = data.getOrDefault("manageDep", assetInfo.get("managedep")),
//                    assetModel = data.getOrDefault("assetModel",assetInfo.get("assetmodel")),
//                    assetType = data.getOrDefault("assetType",assetInfo.get("assettype"));
            String assetName = assetInfo.get("assetname"),
                    assetDescribe = assetInfo.get("assetdescribe"),
                    unit = assetInfo.get("unit"),
                    manageDep = assetInfo.get("managedep"),
                    assetModel = assetInfo.get("assetmodel"),
                    assetType = assetInfo.get("assettype");
            //数量有可能负数
            Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
            String  locationCode = data.get("locationCode"),
                    locationDescribe = data.get("locationDescribe"),
                    brand = data.get("brand"),
                    manufacturer = data.get("manufacturer"),
                    FACode = data.get("FACode"),
                    FACategory = data.get("FACategory"),
                    prjNo = data.get("prjNo"),
                    price = data.get("price"),
                    arrivalDate = data.get("arrivalDate"),
                    supplier = data.get("supplier");
            int isAsset = getIsAsset(assetCode, "isAsset");//判断是否為资产
            String itemid = assetInfo.get("id");//物料数据id
            Map<String, String> prInfo = new HashMap<>();
            if(!prid.isEmpty()){
                prInfo = getField1ByPrid(prid,prTable,itemid);
                if(prInfo == null || prInfo.get("field1").equals("")){
                    result.put("msg", "prid["+prid+"]申请单中未找到itemcode["+assetCode+"]的倉庫字段");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }

            //20221019 增加倉庫邏輯 采購入庫時根據pr中的倉庫進行倉庫庫存增加 如果没有prid获取默认仓库
            String wareHouse = prid.isEmpty()? assetInfo.get("warehouse") :prInfo.get("field1") ;//存的是倉庫id
            if(wareHouse.isEmpty()){
                result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->或EAP未維護默認倉庫:"+wareHouse);
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
            if(get.execute(sql) && get.next()){
                String wid = get.getString("id");
                String s = "update uf_003_WarehouseNum set num1=num1 + "+quantity+",num3=num3 + "+quantity+" where id="+wid;
                boolean f = set.execute(s);
                log.writeLog("有倉庫庫存-更新倉庫庫存 "+s);
                log.writeLog("更新結果 "+f);
                if(!f){
                    result.put("msg", "itemcode["+assetCode+"]采購入庫更新倉庫庫存失敗");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }

            }else {
                //沒有倉庫記錄  插入
                String s = "insert into uf_003_WarehouseNum" +
                        "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID"+
                        ",assetCode,wareHouse,num1,num2,num3,num4) " +
                        "values(?,?,?,?,?,?,?,?,?,?,?,?)";
                String modedatacreatedate = dateTools.getCurrentDate();
                String modedatacreatetime = dateTools.getCurrentTime();
                String uuid = dateTools.getUUID();
                String uf_003_WareHouseNum_Modeid = new BaseBean().getPropValue("SW003", "uf_003_WareHouseNum_Modeid");
                if(uf_003_WareHouseNum_Modeid.isEmpty()){
                    result.put("msg", "配置文件SW003.peoperties中缺少uf_003_WareHouseNum_Modeid配置項");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
                Object[] objects = new Object[]{
                        uf_003_WareHouseNum_Modeid, 1, 0, modedatacreatedate, modedatacreatetime, uuid,
                        assetInfo.get("id"),wareHouse,quantity,0,quantity,0
                };
                log.writeLog("无倉庫庫存-插入倉庫數據參數");
                log.writeLog(JSONObject.toJSONString(objects));
                boolean f = set.executeUpdate(s,objects);
                if(!f){
                    result.put("msg", "itemcode["+assetCode+"]生成新倉庫庫存記錄失敗");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }
            //出入库日志
            Map<String, String> logMap = new HashMap();
            logMap.put("assetCode", assetCode);
            logMap.put("assetName", assetName);
            logMap.put("quantity", String.valueOf(Math.abs(quantity)));
            logMap.put("requestNumber", poNo.replace("\"",""));
            logMap.put("reason", "采購入庫");
            logMap.put("field1", wareHouse);
            logMap.put("field2", prInfo.get("field2"));
            logList.add(logMap);

            //------分割綫
            param_0.add(uf_003_yyArrivalRecord_Modeid);
            param_0.add(1);
            param_0.add(0);
            param_0.add(dateTools.getCurrentDate());
            param_0.add(dateTools.getCurrentTime());
            param_0.add(dateTools.getUUID());
            param_0.add(getIsAsset(assetCode, "id"));
            param_0.add(assetCode);
            param_0.add(assetName);
            param_0.add(assetDescribe);
            //param_0.add(getAssetUnit(unit));
            param_0.add(unit);
            param_0.add(isAsset);
            //param_0.add(getManageDep(assetCode, "manageDep"));
            param_0.add(manageDep);
            param_0.add(assetModel);
            //param_0.add(getAssetType(assetType));
            param_0.add(assetType);
            param_0.add(quantity);
            param_0.add(locationCode);
            param_0.add(locationDescribe);
            param_0.add(brand);
            param_0.add(manufacturer);
            param_0.add(FACode);
            param_0.add(FACategory);
            param_0.add(prjNo);
            param_0.add(poNo.replace("\"",""));
            param_0.add(price);
            param_0.add(arrivalDate.replace("/", "-"));
            param_0.add(supplier);
            param_0.add(0);
            param_0.add(2);
            param_0.add(prid);
            param_0.add(dateTools.getCurrentDate());
            param_0.add(wareHouse);
            paramsList_0.add(param_0);
            //------分割綫
            //if(isAsset==1){
            //非資產的需要入庫
            param_1.add(quantity);
            param_1.add(quantity);
            param_1.add(assetCode);
            paramsList_1.add(param_1);
            //}
        }
//        RecordSetTrans rs = new RecordSetTrans();
//        rs.setAutoCommit(false);
        if (paramsList_0.size() > 0) {
            log.writeLog(sql_0);
            log.writeLog(JSONObject.toJSONString(paramsList_0));
            try {
                set.executeBatchSql(sql_0, paramsList_0);
            } catch (Exception e) {
                set.rollback();
                result.put("msg", "資產物料采購入庫執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        if (paramsList_1.size() > 0) {
            log.writeLog(sql_1);
            log.writeLog(JSONObject.toJSONString(paramsList_1));
            try {
                set.executeBatchSql(sql_1, paramsList_1);
            } catch (Exception e) {
                set.rollback();
                result.put("msg", "非資產物料采購入庫執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        try{
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorage", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            for (int i = 0; i < logList.size(); i++) {
                Map<String, String> log = logList.get(i);
                loggingDao.wrtieInventoryLog(set,"1", log.get("assetCode"), Double.parseDouble(log.get("quantity")), log.get("requestNumber"), log.get("reason"),log.get("field1"),log.get("field2"),
                        "2","","",log.get("assetName"));
            }
        }catch (Exception e){
            set.rollback();
            result.put("msg", "非資產物料采購入庫最终记录日志异常 \n" + e.getMessage());
            result.put("apiStatus", false);
            return result;
        }

        set.commit();
        log.writeLog("权限重构开始=>>>" + dateTools.getCurrentTimes());
        RecordSet getMaxid = new RecordSet();
        getMaxid.execute("select max(id) as maxid from " + assetTable);
        getMaxid.next();
        int maxid = getMaxid.getInt("maxid");
        for (int i = maxid; i > maxid - paramsList_0.size(); i--) {
            dbTools.refreshRight(1, Util.getIntValue(uf_003_yyArrivalRecord_Modeid, 0), i);
        }
        log.writeLog("权限重构结束=>>>" + dateTools.getCurrentTimes());


        return result;
    }

    /**
     * 采購退貨 isAsset為Y时檢查對應記錄是否登記了資產，如已登記數量不足扣減返回提示需要在EAP走報廢，
     * 為N時查詢物料表剩餘庫存是否足夠扣，剩餘足夠扣減時減少庫存並生成出庫記錄，不足時返回提示需要在EAP進行歸還
     * @param requestParams
     * @return
     */
    public Map<String, Object> PurchaseStorageReturn(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("采購退貨參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "采購退貨缺少必要参数datas");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        Map<String, Object> check1 = checkDetails(datas);
        boolean checkResult1 = (boolean) check1.get("apiStatus");
        if (!checkResult1) {
            result.put("msg", "檢查物料信息參數失敗 " + check1.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        String prTable = getPropValue("SW003","prTable");
        Map<String, Object> checkPR = checkPR(datas,false);
        boolean checkResult_PR = (boolean) checkPR.get("apiStatus");
        if (!checkResult_PR) {
            result.put("msg", "檢查PO关联PR記錄:" + checkPR.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        RecordSetTrans set = new RecordSetTrans();//更新仓库库存何报废资产
        set.setAutoCommit(false);

        Map<String, Object> check2 = checkPO(datas);
        boolean checkResult2 = (boolean) check2.get("apiStatus");
        if (!checkResult2) {
            result.put("msg", "檢查PO入庫記錄:" + check2.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        String sql_1 = "update " + assetTable + " set totalQuantity=totalQuantity-?,InventoryQuantity=InventoryQuantity-? where " + tableKey + "=?";
        String sql_0 = "update uf_003_yyArrivalRecord set quantity=quantity-? where id=?";
        List<List<Object>> paramsList_0 = new ArrayList<>();//是资产
        List<List<Object>> paramsList_1 = new ArrayList<>();//不是资产
        List<Map<String, String>> logList = new ArrayList<>();
        RecordSet checkPO = new RecordSet();
        RecordSet is = new RecordSet();
        RecordSet newRs = new RecordSet();
        RecordSet get = new RecordSet();

        for (Map<String, String> data : datas) {
            List<Object> param_0 = new ArrayList<>();
            List<Object> param_1 = new ArrayList<>();
            String assetCode = data.get("assetCode");
            Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(newRs,assetCode);
            String poNo = data.get("poNo");
            String prid = data.getOrDefault("prid","");

            Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
            int isAsset = getIsAsset(assetCode, "isAsset");
            String itemid = assetInfo.get("id");//物料数据id
            Map<String, String> prInfo = new HashMap<>();
            if(!prid.isEmpty()){
                prInfo = getField1ByPrid(prid,prTable,itemid);
                if(prInfo == null || prInfo.get("field1").equals("")){
                    result.put("msg", "prid["+prid+"]申请单中未找到itemcode["+assetCode+"]的倉庫信息");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }

            //20221019 增加倉庫邏輯 退庫時根據pr中的倉庫進行倉庫庫存增加
            String wareHouse = prid.isEmpty()?assetInfo.get("warehouse"):prInfo.get("field1");//存的是倉庫id
            if(wareHouse.isEmpty()){
                result.put("msg", "itemcode["+assetCode+"]采購退庫更新倉庫庫存失敗-->或EAP未維護默認倉庫:"+wareHouse);
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
            if(get.execute(sql) && get.next()){
                String wid = get.getString("id");
                boolean f = set.execute("update uf_003_WarehouseNum set num1=num1-"+quantity+",num3=num3-"+quantity+" where id="+wid);
                if(!f){
                    set.rollback();
                    result.put("msg", "itemcode["+assetCode+"]采購退庫更新倉庫庫存失敗");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }else{
                set.rollback();
                result.put("msg", "itemcode["+assetCode+"]未查詢到EAP中的倉庫庫存記錄");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            Map<String, String> logMap = new HashMap();
            logMap.put("assetCode", assetCode);
            logMap.put("assetName", assetInfo.get("assetname"));
            logMap.put("quantity", String.valueOf(Math.abs(quantity)));
            logMap.put("requestNumber", "退貨-" + poNo);
            logMap.put("reason", "退貨");
            logMap.put("field1", wareHouse);
            logMap.put("field2", prInfo.get("field2"));
            logList.add(logMap);
            //isAsset == 0 为资产型
            if (isAsset == 0) {
                checkPO.execute("select * from uf_003_yyArrivalRecord where poCode='" + poNo + "' and itemcode='" + assetCode + "'");
                if (checkPO.next()) {
                    Double assetNums = checkPO.getDouble("assetNums");//已登記的資產數量
                    Double _quantity = checkPO.getDouble("quantity");//采購入庫數量
                    int id = checkPO.getInt("id");
                    //资产物料如果未登记
                    if (assetNums == 0.0 || Double.valueOf(assetNums).intValue() ==0) {
                        //刪除入庫記錄--先插入
                        String insertSql = "insert into uf_003_Arrival_del(oldid,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                                "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName)\n" +
                                "select id,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                                "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName\n" +
                                "from uf_003_yyArrivalRecord where id=" + id;
                        is.execute(insertSql);
                        is.execute("delete from uf_003_yyArrivalRecord where id=" + id);

                        //減少物料表中的庫存數量
                        param_1.add(quantity);
                        param_1.add(quantity);
                        param_1.add(assetCode);
                        paramsList_1.add(param_1);
                    } else {
                        //減少采購入庫記錄中的quantity （去掉已登記的）
                        //如果退庫數量超過剩餘可退庫的，入庫記錄減少退庫數量-已登記的，否則使用退庫數量
                        param_0.add(quantity>(_quantity - assetNums) ? (quantity - assetNums) : quantity);
                        param_0.add(id);
                        paramsList_0.add(param_0);

                        //減少物料表中的庫存數量
                        param_1.add(quantity);
                        param_1.add(quantity);
                        param_1.add(assetCode);
                        paramsList_1.add(param_1);
                    }
                }else{
                    set.rollback();
                    result.put("msg", "prid["+prid+"] poNo["+poNo+"]未找到uf_003_yyArrivalRecord表中的采購入庫記錄");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            } else {
                //非資產物料操作庫存
                checkPO.execute("select * from uf_003_yyArrivalRecord where poCode='" + poNo + "' and itemcode='" + assetCode + "'");
                if (checkPO.next()) {
                    Double quantity_get = checkPO.getDouble("quantity");
                    int id = checkPO.getInt("id");
                    //如果本次退库数量与入库一致
                    if ( (quantity_get-quantity)==0 || (quantity_get-quantity)==0.00) {
                        //刪除入庫記錄--先插入
                        String insertSql = "insert into uf_003_Arrival_del(oldid,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                                "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName)\n" +
                                "select id,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                                "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName\n" +
                                "from uf_003_yyArrivalRecord where id=" + id;
                        is.execute(insertSql);
                        is.execute("delete from uf_003_yyArrivalRecord where id=" + id);

                        //減少物料表中的庫存數量
                        param_1.add(quantity);
                        param_1.add(quantity);
                        param_1.add(assetCode);
                        paramsList_1.add(param_1);
                    }else{
                        //減少采購入庫記錄中的quantity
                        param_0.add(quantity);
                        param_0.add(id);
                        paramsList_0.add(param_0);

                        //減少物料表中的庫存數量
                        param_1.add(quantity);
                        param_1.add(quantity);
                        param_1.add(assetCode);
                        paramsList_1.add(param_1);
                    }
                }else{
                    set.rollback();
                    result.put("msg", "prid["+prid+"] poNo["+poNo+"]未找到uf_003_yyArrivalRecord表中的采購入庫記錄");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }
        }
//        RecordSetTrans rs = new RecordSetTrans();
//        rs.setAutoCommit(false);
        if (paramsList_0.size() > 0) {
            try {
                set.executeBatchSql(sql_0, paramsList_0);
                log.writeLog("退库減少采購入庫記錄中的quantity");
                log.writeLog(JSONObject.toJSONString(paramsList_0));
            } catch (Exception e) {
                set.rollback();
                result.put("msg", "退库減少采購入庫記錄中的quantity執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        if (paramsList_1.size() > 0) {
            try {
                set.executeBatchSql(sql_1, paramsList_1);
                log.writeLog("退库減少物料表中的庫存數量");
                log.writeLog(JSONObject.toJSONString(paramsList_1));
            } catch (Exception e) {
                set.rollback();
                result.put("msg", "退库減少物料表中的庫存數量執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        //檢查采購記錄時需要報廢資產
        log.writeLog("檢查采購記錄時需要報廢資產");
        log.writeLog(JSONObject.toJSONString(check2));
        if((boolean)check2.get("AssetRei")){
            try {
                Map<String,Object>  AssetRei = AssetRei(datas);
                log.writeLog(JSONObject.toJSONString(AssetRei));
                if (!(boolean) AssetRei.get("apiStatus")) {
                    set.rollback();
                    result.put("msg", "采購退庫發起資產報廢失敗:" + AssetRei.get("msg"));
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }catch (Exception e){
                set.rollback();
                e.printStackTrace();
                result.put("msg", "采購退庫發起資產報廢異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }

        try{
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturn", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            for (int i = 0; i < logList.size(); i++) {
                Map<String, String> log = logList.get(i);
                loggingDao.wrtieInventoryLog(set,"1", log.get("assetCode"), Double.parseDouble(log.get("quantity")), log.get("requestNumber"), log.get("reason"),log.get("field1"),log.get("field2"),
                        "3","","",log.get("assetName"));
            }
        }catch (Exception e){
            set.rollback();
            e.printStackTrace();
            result.put("msg", "采購退庫最终记录日志异常 \n" + e.getMessage());
            result.put("apiStatus", false);
            return result;
        }

        set.commit();
        return result;
    }

    /**
     * 检查物料-单条
     * @param data
     * @return
     */
    public Map<String, Object> checkMain(Map<String, String> data) {
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();
        if (!data.containsKey("assetCode")) {
            result.put("msg", "data中缺少參數assetCode");
            result.put("apiStatus", false);
            return result;
        }
        String assetCode = data.get("assetCode");
        rs.execute("select * from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
        if (!rs.next()) {
            result.put("msg", "EAP庫中不存在assetCode[" + assetCode + "]");
            result.put("apiStatus", false);
        } else {
            result.put("apiStatus", true);
        }
        return result;
    }

    /**
     * 检查物料-明细
     * @param datas
     * @return
     */
    public Map<String, Object> checkDetails(List<Map<String, String>> datas) {
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        for (Map<String, String> data : datas) {
            if (!data.containsKey("assetCode")) {
                result.put("msg", "data中缺少參數assetCode");
                result.put("apiStatus", false);
                break;
            }
            String assetCode = data.get("assetCode");
            rs.execute("select * from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
            if (!rs.next()) {
                result.put("msg", "EAP庫中不存在assetCode[" + assetCode + "]");
                result.put("apiStatus", false);
                break;
            }
        }
        return result;
    }

    /**
     * 检查物料-批量新增保存
     * @param datas
     * @return
     */
    public Map<String, Object> checkDetailsForSave(List<Map<String, String>> datas) {
        RecordSet rs = new RecordSet();
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        for (Map<String, String> data : datas) {
            if (!data.containsKey("assetCode")) {
                result.put("msg", "data中缺少參數assetCode");
                result.put("apiStatus", false);
                break;
            }
            String assetCode = data.get("assetCode");
            rs.execute("select * from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
            if (rs.next()) {
                result.put("msg", "EAP庫中已存在assetCode[" + assetCode + "]");
                result.put("apiStatus", false);
                break;
            }
        }
        return result;
    }

    /**
     * 退貨時檢查PR
     * @param datas
     * @param realCheck 是否校验prid跟OA的流程关联
     * @return
     */
    public Map<String, Object> checkPR(List<Map<String, String>> datas,boolean realCheck) {
        RecordSet checkPO = new RecordSet();
        RecordSet checkAsset = new RecordSet();
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        for (Map<String, String> data : datas) {

            if(!data.containsKey("prid") && realCheck){
                result.put("msg", "退库行数据中存在缺少prid参数");
                return result;
            }
            String prid = "";
            prid = data.get("prid").replace("\"","");;
            if (prid.isEmpty() && realCheck) {
                result.put("msg", "退库行数据中存在参数prid為空,請檢查");
                result.put("apiStatus", false);
                return result;
            }
            //prid不为空 realCheck为trye时判断prid是否为OA中PR流程的请求id
            if(!prid.isEmpty() && realCheck){
                //根据requestid查询PR
                //String prTable = dbTools.getBillTableName(prid);
                String prTable = getPropValue("SW003","prTable");
                if(prTable.isEmpty()){
                    result.put("msg", "获取SW003.properties中的prTable为空");
                    result.put("apiStatus", false);
                    return result;
                }
                RecordSet checkPR = new RecordSet();
                checkPR.execute("select requestid,id from "+prTable+" where requestid="+prid);
                if(!checkPR.next()){
                    result.put("msg", "根据prid["+prid+"]查询pr流程["+prTable+"]为空");
                    result.put("apiStatus", false);
                    return result;
                }
            }
        }
        return result;
    }


    /**
     * 退貨時檢查數量 如果資產已經登記則發起資產報廢
     * @param datas
     * @return
     */
    public Map<String, Object> checkPO(List<Map<String, String>> datas) {
        RecordSet checkPO = new RecordSet();
        RecordSet checkAsset = new RecordSet();
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("AssetRei", false);
        for (Map<String, String> data : datas) {
            String assetCode = data.get("assetCode");
            String poNo = data.get("poNo");
            //String prid = data.get("prid").replace("\"","");;
            Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
            int isAsset = getIsAsset(assetCode, "isAsset");
            if (isAsset == 0) {
                //根據poNo和assetCode查詢入庫記錄表中是否存在
                checkPO.execute("select * from uf_003_yyArrivalRecord where poCode='" + poNo + "' and itemcode='" + assetCode + "'");
                if (checkPO.next()) {
                    //資產 判斷是否已經登記過
                    Double assetNums = checkPO.getDouble("assetNums");//已登記的數量
                    Double _quantity = checkPO.getDouble("quantity");//采購入庫數量
                    if (quantity > _quantity) {
                        result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "]本次退貨數量[" + quantity + "]超過采購入庫數量[" + _quantity + "]");
                        result.put("apiStatus", false);
                        return result;
                    }
                    //采購入庫數量-已登記數量小於退貨數量
                    if (quantity > (_quantity - assetNums)) {
                        result.put("AssetRei", true);
                        result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "]本次退貨數量[" + quantity + "]超過剩餘可退數量[" + (_quantity - assetNums) + "],請在EAP發起資產報廢");
//                        result.put("apiStatus", false);
                        return result;
                    }
                } else {
                    result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "]未在EAP中進行過采購入庫");
                    result.put("apiStatus", false);
                    return result;
                }
            } else {
                //根據poNo和assetCode查詢入庫記錄表中是否存在
                checkPO.execute("select * from uf_003_yyArrivalRecord where poCode='" + poNo + "' and itemcode='" + assetCode + "'");
                if (checkPO.next()) {
                    //判斷非資產物料的剩餘庫存
                    checkAsset.execute("select * from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
                    checkAsset.next();
                    Double InventoryQuantity = checkAsset.getDouble("InventoryQuantity");//庫存數量
                    if (quantity > InventoryQuantity) {
                        result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "]本次退貨數量[" + quantity + "]超過EAP該物料剩餘庫存數量[" + InventoryQuantity + "],請讓業務部門在EAP中進行歸還");
                        result.put("apiStatus", false);
                        return result;
                    }
                } else {
                    result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "]未在EAP中進行過采購入庫");
                    result.put("apiStatus", false);
                    return result;
                }

            }
        }
        return result;
    }

    /**
     * 退貨時資產已經登記則發起資產報廢 2023年3月16日
     * @param datas
     * @return
     */
    public Map<String, Object> AssetRei(List<Map<String, String>> datas) {
        RecordSet checkAsset = new RecordSet();
        RecordSet get = new RecordSet();
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        try{
            for (Map<String, String> data : datas) {
                String assetCode = data.get("assetCode");
                String poNo = data.get("poNo");
                String prid = data.get("prid").replace("\"","");;
                Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
                try {
                    //退庫增加資產報廢邏輯 2023年3月16日
                    log.writeLog("poNo[" + poNo + "]中的assetCode[" + assetCode + "]本次退貨數量[" + quantity + "]超過剩余可退货的數量,進行資產報廢");
                    String wfid03 = new BaseBean().getPropValue("SW003", "wfid03");
                    String table03 = new BaseBean().getPropValue("SW003", "table03");
                    String martix = new BaseBean().getPropValue("SW003", "martix");
                    if(wfid03.isEmpty() || table03.isEmpty() || martix.isEmpty()){
                        result.put("msg", "采購退貨發起資產報廢流程>>SW003.properties中未找到參數(wfid03,table03,martix)");
                        result.put("apiStatus", false);
                        return result;
                    }
                    //1、先查詢用該記錄登記的資產
                    String sql = "select * from uf_003_AssetInfo2 where poCode='"+poNo+"'";
                    if(checkAsset.execute(sql)){
                        Map<String,String> maindata = new HashMap<>();
                        List<Map<String,Object>> detaildata = new ArrayList<>();
                        while (checkAsset.next()){
                            String id = checkAsset.getString("id");
                            String superDataid = checkAsset.getString("superDataid");
                            String wareHouse = checkAsset.getString("wareHouse");
                            String managerDep = checkAsset.getString("managerDep");
                            String code = checkAsset.getString("assetCode");
                            String location = checkAsset.getString("location");
                            String locationDescribe = checkAsset.getString("locationDescribe");
                            String serialNo = checkAsset.getString("serialNo");
                            String supplier = checkAsset.getString("supplier");
                            String price = checkAsset.getString("price");
                            String addUser = checkAsset.getString("addUser");
                            String oldStatus = checkAsset.getString("assetStatus");

                            maindata.put("applicationUser",addUser);
                            maindata.put("applicationDep",managerDep);
                            maindata.put("applicationDate",dateTools.getCurrentDate());
                            maindata.put("sqlx","1");

                            get.execute(" select depmanager from "+martix +" where depid="+managerDep);
                            get.next();
                            String depManager = get.getString("depmanager");
                            Map<String,Object> detail = new HashMap<>();
                            detail.put("applicationQuantity",1);
                            detail.put("SerialNumber",serialNo);
                            detail.put("depOfAsset",managerDep);
                            detail.put("depManager",depManager);//管理部門負責人
                            detail.put("oldStatus",oldStatus);
                            detail.put("reason","采購退貨");
                            detail.put("amount",price);
                            detail.put("mainAssetCode",id);
                            detail.put("location",location);
                            detail.put("locationDesc",locationDescribe);
                            get.execute("select fat from uf_003_CI2Manager where dep="+managerDep);
                            get.next();
                            detail.put("Fat",get.getString("fat"));
                            detaildata.add(detail);
                        }
                        ReqOperateRequestEntity requestParam = new ReqOperateRequestEntity();
                        //流程流转扩展参数
                        Map <String,Object> otherParams = new HashMap<>();
                        otherParams.put("isVerifyPer","0"); //不验证用户创建流程权限

                        requestParam.setMainData(getFormMainData(maindata));
                        requestParam.setDetailData(getFormDetailData(detaildata,table03));
                        requestParam.setWorkflowId(Integer.parseInt(wfid03));
                        requestParam.setRequestName("采購退貨資產報廢 "+dateTools.getCurrentDate());
                        requestParam.setOtherParams(otherParams);

                        WorkflowRequestOperatePA operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
                        User user = new User(Integer.parseInt(maindata.get("applicationUser")));
                        PAResponseEntity respose = operatePA.doCreateRequest(user,requestParam);

                        log.writeLog("采購退貨發起資產報廢 "+JSONObject.toJSONString(respose));
                        log.writeLog(respose.getCode().getStatusCode()+"  "+respose.getCode().getMessage());
                        if(respose.getCode().getStatusCode()>1){
                            result.put("msg", JSONObject.toJSONString(respose.getCode().getMessage()));
                            result.put("apiStatus", false);
                            return result;
                        }
                    }else{
                        result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "],未查詢到已登記的資產");
                        result.put("apiStatus", false);
                        return result;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("msg", "poNo[" + poNo + "]中的assetCode[" + assetCode + "],關聯資產報廢異常 "+e.getMessage());
                    result.put("apiStatus", false);
                    return result;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("msg", "采購退庫 關聯資產報廢異常2 "+e.getMessage());
            result.put("apiStatus", false);
            return result;
        }

        return result;
    }

    /**
     * 根据code获取用友物料种类建模表id
     * @param code
     * @return
     */
    public int getAssetType(String code) {
        if (code.isEmpty()) return 0;
        RecordSet rs = new RecordSet();
        rs.execute("select id from uf_003_Type where type_code='" + code + "'");
        rs.next();
        return rs.getInt("id");
    }

    /**
     * 根据code获取用友单位建模表id
     * @param code
     * @return
     */
    public int getAssetUnit(String code) {
        if (code.isEmpty()) return 0;
        RecordSet rs = new RecordSet();
        rs.execute("select id from uf_003_unit where unit_code='" + code + "'");
        rs.next();
        return rs.getInt("id");
    }

    /**
     * 根据部门名称获取id
     * @param name
     * @return
     */
    public int getDepartmentid(String name) {
        if (name.isEmpty()) return 0;
        RecordSet rs = new RecordSet();
        rs.execute("select id from hrmdepartment where departmentname='" + name + "'");
        rs.next();
        return rs.getInt("id");
    }

    /**
     * 根据物料编码获取是否為资产（0=资产 1=非资产）,或獲取表id
     * @param assetCode
     * @return
     */
    public int getIsAsset(String assetCode, String field) {
        if (assetCode.isEmpty()) return 1;
        RecordSet rs = new RecordSet();
        rs.execute("select " + field + " from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
        rs.next();
        return rs.getInt(field);
    }

    /**
     * 根据物料编码获取管理部門
     * @param assetCode
     * @return
     */
    public int getManageDep(String assetCode, String field) {
        if (assetCode.isEmpty()) return 0;
        RecordSet rs = new RecordSet();
        rs.execute("select " + field + " from " + assetTable + " where " + tableKey + "='" + assetCode + "'");
        rs.next();
        return rs.getInt(field);
    }

    /**
     * 查询pr明细2的数据
     * @param prid
     * @param prTable
     * @param itemcodeid
     * @return
     */
    public Map<String,String> getField1ByPrid(String prid,String prTable,String itemcodeid){
        Map<String,String> data = new HashMap<>();
        data.put("field1","");
        data.put("field2","");
        data.put("quantity","");
        RecordSet rs = new RecordSet();
        rs.execute("select id from "+prTable+" where requestid="+prid);
        if(rs.next()){
            int mainid = rs.getInt("id");
            rs.execute("select field1,field2,quantity from "+prTable+"_dt2 where mainid="+mainid+" and itemcodesw003="+itemcodeid);
            rs.next();
            data.put("field1",rs.getString("field1"));
            data.put("field2",rs.getString("field1"));
            data.put("quantity",rs.getString("quantity"));
        }
        return data;
    }

    /*--------------------------分割线-----------------------------------*/
    /**
     * 退庫資產發起報廢
     * @return
     */
    private List <WorkflowRequestTableField> getFormMainData(Map<String,String> maindata){
        List <WorkflowRequestTableField> mainFields = new ArrayList <>();

        //申请人
        WorkflowRequestTableField applicationUser = new WorkflowRequestTableField();
        applicationUser.setFieldName("applicationUser");
        applicationUser.setFieldValue(maindata.get("applicationUser"));
        applicationUser.setView(true);
        applicationUser.setEdit(true);
        mainFields.add(applicationUser);

        //申请部門
        WorkflowRequestTableField applicationDep = new WorkflowRequestTableField();
        applicationDep.setFieldName("applicationDep");
        applicationDep.setFieldValue(maindata.get("applicationDep"));
        applicationDep.setView(true);
        applicationDep.setEdit(true);
        mainFields.add(applicationDep);

        //申请日期
        WorkflowRequestTableField applicationDate = new WorkflowRequestTableField();
        applicationDate.setFieldName("applicationDate");
        applicationDate.setFieldValue(maindata.get("applicationDate"));
        applicationDate.setView(true);
        applicationDate.setEdit(true);
        mainFields.add(applicationDate);

        //申請類型
        WorkflowRequestTableField enclosure = new WorkflowRequestTableField();
        enclosure.setFieldName("sqlx");
        enclosure.setFieldValue(maindata.get("sqlx"));
        enclosure.setView(true);
        enclosure.setEdit(true);
        mainFields.add(enclosure);

        return mainFields;
    }

    /**
     * 明细数据
     * @return
     */
    private List<WorkflowDetailTableInfoEntity> getFormDetailData(List<Map<String,Object>> detaildata, String table03){
        List<WorkflowDetailTableInfoEntity> details = new ArrayList<>();
        //明细信息
        WorkflowDetailTableInfoEntity detail2 = new WorkflowDetailTableInfoEntity();
        detail2.setTableDBName(table03);
        //明细行
        WorkflowRequestTableRecord[] detailRows = new WorkflowRequestTableRecord[detaildata.size()];
        WorkflowRequestTableField field = null;
        for(int i=0;i<detaildata.size();i++){
            //明细行字段数据
            Map<String,Object> data = detaildata.get(i);
            WorkflowRequestTableField[] rowDatas = new WorkflowRequestTableField[data.size()];

            log.writeLog(JSONObject.toJSONString(data));
            int index = 0;
            for (Map.Entry<String,Object> entry : data.entrySet()){
                //行字段数据
                field = new WorkflowRequestTableField();
                field.setFieldName(entry.getKey());
                field.setFieldValue(String.valueOf(entry.getValue()));
                field.setView(true);
                field.setEdit(true);
                rowDatas[index] = field;
                index ++;
            }
            WorkflowRequestTableRecord row = new WorkflowRequestTableRecord();
            row.setRecordOrder(0);
            row.setWorkflowRequestTableFields(rowDatas);
            detailRows[i] = row;
        }
        detail2.setWorkflowRequestTableRecords(detailRows);
        details.add(detail2);

        return details;
    }

}
